<template>
  <a-modal
    v-model:visible="visible"
    :mask-closable="false"
    :keyboard="false"
    ok-text="确定"
    cancel-text="取消"
    :body-style="{ padding: '0 0 12px 0' }"
    :destroy-on-close="true"
    @ok="submit"
  >
    <a-card>
      <a-alert v-if="errorMessage" type="error" :message="errorMessage" banner />
      <div class="choose-member">
        <a-tabs v-model:activeKey="activeKey" @change="change">
          <a-tab-pane v-if="props.gainType === 'user' || !props.gainType" key="0" tab="人员">
            <a-input
              v-model:value="queryInfo"
              placeholder="按用户名模糊搜索"
              clearable
              style="width: 200px"
              @pressEnter="userData(true)"
            />

            <div class="tree-content">
              <a-tree
                v-if="userTreeData.length"
                v-model:selectedKeys="selectedKeys"
                v-model:checkedKeys="checkedKeys"
                default-expand-all
                checkable
                :check-strictly="true"
                :height="433"
                :tree-data="userTreeData"
                @check="checkNode"
              >
                <template #title="{ title, key, roleListText }">
                  <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
                  <template v-else>
                    {{ title }}
                    <div v-if="roleListText" class="roleList">
                      【
                      <p :title="roleListText">{{ roleListText }}</p>
                      】
                    </div>
                  </template>
                </template>
              </a-tree>
            </div>

            <div>
              <IcpEmpty v-if="userTreeData.length === 0" :description="'暂无数据'" />
            </div>
          </a-tab-pane>
          <a-tab-pane v-if="props.gainType === 'role' || !props.gainType" key="1" tab="角色">
            <a-input
              v-model:value="queryInfo"
              placeholder="根据角色名称模糊搜索"
              clearable
              style="width: 200px"
              @pressEnter="roleData(true)"
            />

            <div class="tree-content">
              <a-tree
                v-if="roleTreeData.length"
                v-model:selectedKeys="selectedKeys"
                v-model:checkedKeys="checkedKeys"
                default-expand-all
                checkable
                :check-strictly="true"
                :height="433"
                :tree-data="roleTreeData"
                @check="checkNode"
              >
                <template #title="{ title, key }">
                  <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
                  <template v-else>{{ title }} </template>
                </template>
              </a-tree>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>
  </a-modal>
</template>
<script lang="ts" setup name="ChooseMember">
import { ref, watch, onMounted } from 'vue'
import { getOrgUserList } from '@@/api/system/user'
import { getOrgRoleList, getRoleListSort } from '@@/api/system/role'
import { useUserStoreWidthOut } from '@/store/modules/user'
import { getOrgProjectUserList } from '@@/api/project'
import { isConfig } from '@@/utils/index'
import { message, Modal } from 'ant-design-vue'
import { Form } from 'ant-design-vue'

const formItemContext = Form.useInjectFormItemContext()

const emit = defineEmits(['close'])
const queryInfo = ref('')
const activeKey = ref<string | number>('0')
const visible = ref<boolean>(false)
const selectedKeys = ref<string[]>([])
const checkedKeys = ref<string[]>([])
const userTreeData = ref<any>([])
const roleTreeData = ref<any>([])
const checkedResult = ref<any>([])
const userStore: any = useUserStoreWidthOut()
const userList = ref([])

const props = defineProps({
  choosedKeys: {
    type: Array,
    default: () => []
  },
  isShow: {
    type: Boolean,
    default: false
  },
  memberType: {
    type: [Number, String],
    default: 0
  },
  userType: {
    type: String,
    default: 'org'
  },
  projectId: {
    type: String,
    default: ''
  },
  gainType: {
    type: String,
    default: ''
  },
  roleType: {
    type: String,
    default: 'all' // all 项目角色和组织角色  org 组织角色  project 项目角色
  }
})
const myRoleType = ref(props.roleType)
if (isConfig()) {
  // 运维端只能查组织角色
  myRoleType.value = 'org'
}

watch(
  () => visible.value,
  (nValue) => {
    if (nValue) {
      userTreeData.value = []
      roleTreeData.value = []
      queryInfo.value = ''
      activeKey.value = props.memberType.toString()
      checkedKeys.value = props.choosedKeys.map((el: any) => el.value)
      checkedResult.value = props.choosedKeys
      initData()
    }
  }
)
onMounted(() => {
  activeKey.value = props.memberType.toString()
  initData()
})
const initData = (isSearch = false) => {
  if (props.gainType === 'user' || !props.gainType) {
    if (props.gainType === 'user') {
      activeKey.value = '0'
    }
    userData(isSearch)
  }
  if (props.gainType === 'role' || !props.gainType) {
    if (props.gainType === 'role') {
      activeKey.value = '1'
    }
    roleData(isSearch)
  }
}
const userData = (isSearch) => {
  const param: any = {
    appId: userStore.getAppId,
    orgId: userStore.getOrgId,
    pageNum: 1,
    pageSize: 500,
    availableFlag: 1 // 过滤掉停用用户
  }
  if (isSearch) {
    param.queryInfo = queryInfo.value
  }
  let fn
  if (props.userType === 'project') {
    param.projectId = props.projectId
    fn = getOrgProjectUserList
  } else {
    fn = getOrgUserList
  }
  userTreeData.value = []
  fn(param).then((res: any) => {
    const tempArr = res.list.filter((item) => {
      return item.accountProjectStatus !== 0
    })
    if (tempArr.length) {
      userList.value = tempArr.map((item) => {
        return {
          title: item.name,
          key: item.userId,
          accountId: item.accountId,
          roleListText: getRoleList(item.userRoleList)
        }
      })
      userTreeData.value = [
        {
          title: userStore.getOrgInfo.orgName,
          key: userStore.getOrgId,
          disableCheckbox: true,
          children: userList.value
        }
      ]
    }
  })
}

const roleData = (isSearch) => {
  const param: any = {
    orgId: userStore.getOrgId
  }
  if (isConfig()) {
    param.appId = ''
    param.appIdList = '3050096807037108231,3120223396747542530'
  } else {
    param.appId = userStore.getAppId
  }
  if (isSearch) {
    param.queryInfo = queryInfo.value
  }
  if (myRoleType.value === 'project') {
    param.isProject = 0 // 是否为项目，0是1否
    param.suitOrgType = 1 // 是否为研究机构
  }
  const fnUrl = myRoleType.value === 'project' ? getRoleListSort : getOrgRoleList
  fnUrl(param).then((res: any) => {
    roleTreeData.value = []
    res.forEach((item) => {
      if (props.projectId && item.flag === 0) {
        return
      }
      // const tempArr: any = []
      // if (item.roleList && item.roleList.length > 0) {
      // const roleMark = ['机构角色', '专业角色', '伦理委员会', 'CRO', 'SMO', '申办方', '其他']
      // item.roleList.forEach((item) => {
      let title = item.roleName

      if (item.roleClass === 2) {
        title = title + '【自定义角色】'
      }
      roleTreeData.value.push({
        title: title,
        titleLabel: title,
        key: item.roleId,
        isProject: item.isProject
      })
    })
  })
}

const getRoleList = (userRoleList) => {
  let roleList = ''
  if (Array.isArray(userRoleList) && userRoleList.length) {
    roleList = userRoleList
      .map((item) => item.roleName)
      .filter((item) => item)
      .join('，')
  }
  return roleList
}

const errorMessage = ref()
const submit = () => {
  try {
    if (checkedResult.value.length === 0) {
      throw new Error(`当前什么都没有选择！`)
    }
  } catch (e: any) {
    // message.error(e.message)
    errorMessage.value = e.message
    setTimeout(() => {
      errorMessage.value = ''
    }, 2000)
    // message.error({
    //   content: e.message,
    //   duration: 30,
    //   class: 'message-error',
    //   style: {
    //     position: 'fixed',
    //     width: '100%',
    //     zIndex: 9999999
    //   }
    // })
    return false
  }
  visible.value = false
  emit('close', { type: activeKey.value, data: checkedResult.value })
  formItemContext.onFieldChange()
}
const change = () => {
  queryInfo.value = ''
  if (checkedResult.value.length === 0) {
    return
  }
  // 弹窗确认
  Modal.confirm({
    title: '提示',
    content: '切换类型选型卡，之前的内容将被清空，请确认后再操作',
    zIndex: 999999,
    centered: true,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      checkedResult.value = []
      checkedKeys.value = []
      message.success({
        content: 'ok',
        style: {
          display: 'none'
        }
      })
    },
    onCancel: () => {
      if (activeKey.value === '1') {
        activeKey.value = '0'
      } else {
        activeKey.value = '1'
      }
      message.success({
        content: 'cancel',
        style: {
          display: 'none'
        }
      })
    }
  })
}
const checkNode = (_, e) => {
  const currItem = e.node.dataRef
  const isHasItemIndex = checkedResult.value.findIndex((el) => el.value === currItem.key)
  if (isHasItemIndex > -1) {
    checkedResult.value.splice(isHasItemIndex, 1)
  } else {
    checkedResult.value.push({
      label: currItem.title,
      value: currItem.key,
      titleLabel: currItem.titleLabel,
      accountId: currItem.accountId,
      isProject: currItem.isProject
    })
  }
}
const show = () => {
  visible.value = true
}

defineExpose({
  show
})
</script>
<style lang="less" scoped>
.tree-content {
  margin-top: 20px;
}
.form-footer {
  border-top: 1px solid #ccc;
  padding-top: 20px;
  text-align: right;

  .ant-btn {
    margin-right: 10px;
  }
  .ant-btn:last-child {
    margin-right: 0;
  }
}
.roleList {
  display: inline-block;
  vertical-align: bottom;
  margin-left: 3px;

  & > p {
    display: inline-block;
    margin: 0;
    max-width: 200px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    vertical-align: bottom;
    // color: #333;
  }
}
</style>
